package com.wen.big_event.interceptors;

import com.wen.big_event.utils.JwtUtil;
import com.wen.big_event.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    //拦截器定义
    //没有token就不让进入到其他页面
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从Autorization这个键里面取值出来，就是我们登录以后传过来的token
        String token = request.getHeader("Authorization");

        try {

            //校验token是否合规
            Map<String,Object> claims = JwtUtil.parseToken(token);
            //使用多线程来确保线程安全问题
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (Exception e) {
           // throw new RuntimeException(e);
            //设置返回的code值
            response.setStatus(401);
            //不放行
            return false;
        }

    }
}
